package algorithms;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author lizen
 */
public class DuplicatedAlphabetInString {
    public static void test() {
        String[] initString = new String[]{"hello bot", "guangzhou", "Shanghai"} ;
        List<String> strArr = Arrays.stream(initString).map(String::toLowerCase)
                .map(DuplicatedAlphabetInString::getFirstDuplicated).toList();
        System.out.println(strArr);

        Arrays.stream(initString).map(String::toLowerCase)
                .map(DuplicatedAlphabetInString::getDuplicated)
                .map(s -> s.entrySet().stream().filter(q -> q.getValue() > 1).toList())
                .forEach(s -> {
                    for (Map.Entry<String, Integer> entry : s){
                        System.out.println(entry.getKey() + ": "+ entry.getValue());
                    }
                });


    }

    public static String getFirstDuplicated(String str) {
        Map<String, Integer> hs = new HashMap<>();
        String result;
        result = "";
        for(int index = 0; index < str.length(); index++){
            char charVal = str.charAt(index);
            String strVal = String.valueOf(charVal);
            if (hs.containsKey(strVal)){
                result = strVal;
                break;
            } else {
                hs.put(strVal, 1);
            }
        }

        return result;
    }

    public static Map<String, Integer> getDuplicated(String str) {
        Map<String, Integer> resultMap = new HashMap<>();

        for(int index = 0; index < str.length(); index++){
            char charVal = str.charAt(index);
            String strVal = String.valueOf(charVal);

            if (strVal.isEmpty()) {
                continue;
            }

            if (resultMap.containsKey(strVal)){
                Integer count = resultMap.get(strVal);
                resultMap.put(strVal, ++count);
            } else {
                resultMap.put(strVal, 1);
            }
        }

        return resultMap;
    }
}
